package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.util.ArrayMap;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.DataConverter;
import com.lily.aidouzixun.util.FileManager;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.lang.ref.WeakReference;

/**
 * 发表动态的Activity
 */
public class PublishDynamicActivity extends Activity {
    private static final String TAG = "PublishDynamicActivity";

    private TitleBar mTitleBar;
    private ProgressDialog mProgressDialog;
    private EditText etPublicDiscuss;
    private ImageView ivPublicDiscuss;

    private Activity mActivity;
    private Context mContext;
    private String key = "";
    private MyHandler mHandler;
    private String backTitle;
    private static final String TITLE = "发表";
    private String discussContent = "";  //动态内容
    private Bitmap discussPhoto;
    private String discussPhotoPath;    //图片真实路径
    private final static String[] setAvatarItems = new String[] {"选择本地照片", "拍照"};

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.publish_discuss_activity);
        init();
        findViews();
        setListeners();
    }
    /**
     * 初始化参数
     */
    private void init() {
        this.key += this.hashCode();
        mActivity = PublishDynamicActivity.this;
        mContext = PublishDynamicActivity.this;
        //得到返回标题
        Intent intent = getIntent();
        backTitle = intent.getStringExtra(MyConstant.IntentKey.BACK_TITLE);
        mHandler = new MyHandler(mActivity);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
        if (Validator.isEffective(MyConfig.getPublishDiscussFail(mContext))) {
            discussContent = MyConfig.getPublishDiscussFail(mContext);
        }
    }
    /**
     * 找到控件
     */
    private void findViews() {
        //标题栏
        mTitleBar = (TitleBar) findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);
        etPublicDiscuss = (EditText) this.findViewById(R.id.et_publish_discuss);
        etPublicDiscuss.requestFocus();
        if (Validator.isEffective(discussContent)) {
            etPublicDiscuss.setText(discussContent);
            etPublicDiscuss.setSelection(discussContent.length());
        }
        ivPublicDiscuss = (ImageView) this.findViewById(R.id.iv_publish_discuss);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //对发表的监听
        mTitleBar.setRightOperation("发表", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                discussContent = etPublicDiscuss.getText().toString().trim();
                publicDiscussText();    //发表动态文字
            }
        });
        //图片的监听
        ivPublicDiscuss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Validator.isEffective(discussPhotoPath)) {
                    Intent intent = new Intent(mContext, ShowImageActivity.class);
                    intent.putExtra(MyConstant.IntentKey.IMAGE_FROM, ShowImageActivity.ImageFrom.FILE_PATH);
                    intent.putExtra(MyConstant.IntentKey.IMAGE_PATH, discussPhotoPath);
                    startActivity(intent);
                } else {
                    HardWare.closeKeyBoard(mContext, etPublicDiscuss);
                    showDiscussPhotoDialog();
                }
            }
        });
    }
    /**
     * 显示上传动态图片的对话框
     */
    private void showDiscussPhotoDialog() {
        new AlertDialog.Builder(mContext)
                .setTitle("设置头像")
                .setItems(setAvatarItems, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int which) {
                        switch (which) {
                            case 0:     //本地选取
                                Intent filePhotoIntent = new Intent();
                                filePhotoIntent.setType("image/*");
                                filePhotoIntent.setAction(Intent.ACTION_GET_CONTENT);
                                mActivity.startActivityForResult(filePhotoIntent, MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_PHOTO_BY_IMAGE_REQUESTCODE);
                                break;
                            case 1:
                                if (HardWare.hasSdcard()) {
                                    // 判断储存卡是否可以用
                                    FileManager.deleteFile(FileManager.DISCUSS_PHOTO_PATH);
                                    Intent intentFromCapture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                    intentFromCapture.putExtra(
                                            MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(FileManager.DISCUSS_PHOTO_PATH)));
                                    mActivity.startActivityForResult(intentFromCapture,
                                            MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_PHOTO_BY_CAMERA_REQUESTCODE);
                                } else {
                                    T.longToast(mContext, "未找到存储卡，无法存储照片！");
                                }
                                break;
                            default:
                                break;
                        }
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        dialogInterface.dismiss();
                    }
                })
                .show();
    }
    /**
     * 接收回传信息
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.e(TAG, "onActivityResult: requestCode:"  + requestCode);
        switch (requestCode) {
            case MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_PHOTO_BY_IMAGE_REQUESTCODE:    //通过图片修改头像
                if (data != null) {
                    String realPath = DataConverter.getFilePathByUri(mContext, data.getData());
                    Log.e(TAG, "onActivityResult: realPath:"  + realPath);
                    Bitmap bitmap = HardWare.loadImageFromFilePath(realPath, 640);
                    discussPhotoPath = createImgFile(bitmap);
                    setDiscussPhoto(discussPhotoPath);
                }
                break;
            case MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_PHOTO_BY_CAMERA_REQUESTCODE:    //通过拍照修改头像
                if (HardWare.hasSdcard()) {
                    Bitmap bitmap = HardWare.loadImageFromFilePath(FileManager.DISCUSS_PHOTO_PATH, 640);
                    discussPhotoPath = createImgFile(bitmap);
                    setDiscussPhoto(discussPhotoPath);
                } else {
                    T.longToast(mContext, "未找到存储卡，无法存储照片！");
                }
                break;

            default:
                break;
        }

    }
    /**
     * 压缩图片,并保存到指定文件夹
     */
    private String createImgFile(Bitmap bitmap) {
        String imagepath = null;
        String sign_dir = Environment.getExternalStorageDirectory()
                + File.separator + "/lily/";
        File dirFile = new File(sign_dir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        File file = new File(sign_dir + System.currentTimeMillis() + ".png");
        imagepath = file.getPath();
        saveBitmap(bitmap, file);
        return imagepath;
    }

    public static void saveBitmap(Bitmap bmp, File file) {
        if (bmp != null) {
            try {
                BufferedOutputStream baos = new BufferedOutputStream(new FileOutputStream(file));
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                baos.flush();
                baos.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 设置动态图片
     */
    private void setDiscussPhoto(String  filePath) {
        if (Validator.isEffective(filePath)) {
            discussPhoto = DataConverter.getBitmapFormFilePath(filePath, 80, 80);
            if (discussPhoto != null) {
                ivPublicDiscuss.setImageBitmap(discussPhoto);
            }
        }
    }

    /**
     * 发表评论文字
     */
    private void publicDiscussText(){
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        if (!Validator.isEffective(discussContent)) {
            T.shortToast(mContext, "内容不能为空！");
            return;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.PUBLISH_DISCUSS_TEXT);
        param.put(MyConstant.RequireParams.DISCUSS_CONTENT, discussContent);
        if (Validator.isEffective(discussPhotoPath)) {
            param.put(MyConstant.RequireParams.HAS_IMAGE, 1); //代表有照片
        } else {
            param.put(MyConstant.RequireParams.HAS_IMAGE, 0); //代表无照片
        }
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.PUBLISH_DISCUSS_TEXT);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }
    /**
     * 发表评论照片
     * @param imageName 图片在服务器上的名称，已经存入数据库
     */
    private void publicDiscussPhoto(String imageName){
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        if (!Validator.isEffective(imageName)) {
            T.shortToast(mContext, "上传地址无效");
            return;
        }
        if (!Validator.isEffective(discussPhotoPath)) {
            T.shortToast(mContext, "上传照片无效");
            return;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        param.put(MyConstant.RequireParams.DATA_TYPE, MyConstant.DataType.PUBLISH_DISCUSS_PHOTO);
        param.put(MyConstant.RequireParams.PHOTO_PATH, discussPhotoPath);
        param.put(MyConstant.RequireParams.IMAGE_NAME, imageName);
        param.put(MyConstant.RequireParams.MAP_KEY, this.key + MyConstant.DataType.PUBLISH_DISCUSS_PHOTO);
        param.put(MyConstant.RequireParams.CALL_BACK_HANDLER, mHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final PublishDynamicActivity activity = (PublishDynamicActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:
                            if (MyConstant.DataType.PUBLISH_DISCUSS_TEXT == msg.arg1) {
                                if (activity.mProgressDialog != null) {
                                    activity.mProgressDialog.setMessage("正在发表，请稍等...");
                                    activity.mProgressDialog.show();
                                }
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:
                            if (MyConstant.DataType.PUBLISH_DISCUSS_TEXT == msg.arg1 && !Validator.isEffective(activity.discussPhotoPath)) {
                                if (activity.mProgressDialog != null) {
                                    activity.mProgressDialog.dismiss();
                                }
                            } else if (MyConstant.DataType.PUBLISH_DISCUSS_PHOTO == msg.arg1){
                                if (activity.mProgressDialog != null) {
                                    activity.mProgressDialog.dismiss();
                                }
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED:
                            if (MyConstant.DataType.PUBLISH_DISCUSS_TEXT == msg.arg1) { //发布动态
                                SparseArray<Object> publishResult = (SparseArray<Object>) msg.obj;
                                if (publishResult != null) {
                                    String errno = (String) publishResult.get(0);
                                    if (Validator.isEffective(errno)) {
                                        if ("0" . equals(errno)) {  //发布成功
                                            if (Validator.isEffective(activity.discussPhotoPath)) { //如果有图片，则需要上传图片
                                                //得到上传图片地址，上传图片
                                                String imageName = (String) publishResult.get(2);
                                                Log.e(TAG, "handleMessage: imageName:" + imageName);
                                                if (Validator.isEffective(imageName)) {
                                                    activity.publicDiscussPhoto(imageName);
                                                }
                                            } else {    //只发布文字
                                                T.shortToast(activity, "发布成功！");
                                                Intent intent = new Intent();
                                                intent.putExtra(MyConstant.IntentKey.TAG, 0);
                                                MyConfig.setPublishDiscussFail(activity, null);
                                                activity.setResult(MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_RESULTCODE, intent);
                                                activity.finish();
                                            }
                                        } else {    //发布失败
                                            T.shortToast(activity, "发布失败！");
                                            MyConfig.setPublishDiscussFail(activity, activity.discussContent);
                                        }
                                    }
                                }
                            } else if (MyConstant.DataType.PUBLISH_DISCUSS_PHOTO == msg.arg1) {  //发布照片
                                SparseArray<Object> publishResult = (SparseArray<Object>) msg.obj;
                                if (publishResult != null) {
                                    String errno = (String) publishResult.get(0);
                                    if (Validator.isEffective(errno)) {
                                        if ("200".equals(errno)) {  //发布成功
                                            T.shortToast(activity, "发布成功！");
                                            Intent intent = new Intent();
                                            intent.putExtra(MyConstant.IntentKey.TAG, 0);
                                            MyConfig.setPublishDiscussFail(activity, null);
                                            activity.setResult(MyConstant.IntentForResultCODE.PUBLISH_DISCUSS_RESULTCODE, intent);
                                            activity.finish();
                                        } else {    //发布失败
                                            T.shortToast(activity, "发布失败！");
                                            MyConfig.setPublishDiscussFail(activity, activity.discussContent);
                                        }
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
}
